[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C provides several language features not found in ANSI standard C.
(The ‘-pedantic’ option directs GNU CC to print a warning message if
any of these features is used.) To test for the availability of these
features in conditional compilation, check for a predefined macro
__GNUC__
, which is always defined under GNU CC.
These extensions are available in C and in the languages derived from it, C++ and Objective C. See section Extensions to the C++ Language, for extensions that apply only to C++.
1.1 Statements and Declarations in Expressions | Putting statements and declarations inside expressions. | |
1.2 Locally Declared Labels | Labels local to a statement-expression. | |
1.3 Labels as Values | Getting pointers to labels, and computed gotos. | |
1.4 Nested Functions | As in Algol and Pascal, lexical scoping of functions. | |
1.5 Constructing Function Calls | Dispatching a call to another function. | |
1.6 Naming an Expression’s Type | Giving a name to the type of some expression. | |
1.7 Referring to a Type with typeof | typeof : referring to the type of an expression.
| |
1.8 Generalized Lvalues | Using ‘?:’, ‘,’ and casts in lvalues. | |
1.9 Conditionals with Omitted Operands | Omitting the middle operand of a ‘?:’ expression. | |
1.10 Double-Word Integers | Double-word integers—long long int .
| |
1.11 Complex Numbers | Data types for complex numbers. | |
1.12 Arrays of Length Zero | Zero-length arrays. | |
1.13 Arrays of Variable Length | Arrays whose length is computed at run time. | |
1.14 Macros with Variable Numbers of Arguments | Macros with variable number of arguments. | |
1.15 Non-Lvalue Arrays May Have Subscripts | Any array can be subscripted, even if not an lvalue. | |
1.16 Arithmetic on void - and Function-Pointers | Arithmetic on void -pointers and function pointers.
| |
1.17 Non-Constant Initializers | Non-constant initializers. | |
1.18 Constructor Expressions | Constructor expressions give structures, unions or arrays as values. | |
1.19 Labeled Elements in Initializers | Labeling elements of initializers. | |
1.21 Cast to a Union Type | Casting to union type from any member of the union. | |
1.20 Case Ranges | ‘case 1 ... 9’ and such. | |
1.22 Declaring Attributes of Functions | Declaring that functions have no side effects, or that they can never return. | |
1.23 Prototypes and Old-Style Function Definitions | Prototype declarations and old-style definitions. | |
1.24 Dollar Signs in Identifier Names | Dollar sign is allowed in identifiers. | |
1.25 The Character <ESC> in Constants | ‘\e’ stands for the character <ESC>. | |
1.27 Specifying Attributes of Variables | Specifying attributes of variables. | |
1.26 Inquiring on Alignment of Types or Variables | Inquiring about the alignment of a type or variable. | |
1.28 An Inline Function is As Fast As a Macro | Defining inline functions (as fast as macros). | |
1.29 Assembler Instructions with C Expression Operands | Assembler instructions with C expressions as operands. (With them you can define “built-in” functions.) | |
• Constraints | Constraints for asm operands | |
1.30 Controlling Names Used in Assembler Code | Specifying the assembler name to use for a C symbol. | |
1.31 Variables in Specified Registers | Defining variables residing in specified registers. | |
1.32 Alternate Keywords | __const__ , __asm__ , etc., for header files.
| |
1.33 Incomplete enum Types | enum foo; , with details to follow.
| |
1.34 Function Names as Strings | Printable strings which are the name of the current function. |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A compound statement enclosed in parentheses may appear as an expression in GNU C. This allows you to use loops, switches, and local variables within an expression.
Recall that a compound statement is a sequence of statements surrounded by braces; in this construct, parentheses go around the braces. For example:
({ int y = foo (); int z; if (y > 0) z = y; else z = - y; z; })
is a valid (though slightly more complex than necessary) expression
for the absolute value of foo ()
.
The last thing in the compound statement should be an expression
followed by a semicolon; the value of this subexpression serves as the
value of the entire construct. (If you use some other kind of statement
last within the braces, the construct has type void
, and thus
effectively no value.)
This feature is especially useful in making macro definitions “safe” (so that they evaluate each operand exactly once). For example, the “maximum” function is commonly defined as a macro in standard C as follows:
#define max(a,b) ((a) > (b) ? (a) : (b))
But this definition computes either a or b twice, with bad
results if the operand has side effects. In GNU C, if you know the
type of the operands (here let’s assume int
), you can define
the macro safely as follows:
#define maxint(a,b) \ ({int _a = (a), _b = (b); _a > _b ? _a : _b; })
Embedded statements are not allowed in constant expressions, such as the value of an enumeration constant, the width of a bit field, or the initial value of a static variable.
If you don’t know the type of the operand, you can still do this, but you
must use typeof
(see section Referring to a Type with typeof
) or type naming (see section Naming an Expression’s Type).
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Each statement expression is a scope in which local labels can be
declared. A local label is simply an identifier; you can jump to it
with an ordinary goto
statement, but only from within the
statement expression it belongs to.
A local label declaration looks like this:
__label__ label;
or
__label__ label1, label2, …;
Local label declarations must come at the beginning of the statement expression, right after the ‘({’, before any ordinary declarations.
The label declaration defines the label name, but does not define
the label itself. You must do this in the usual way, with
label:
, within the statements of the statement expression.
The local label feature is useful because statement expressions are
often used in macros. If the macro contains nested loops, a goto
can be useful for breaking out of them. However, an ordinary label
whose scope is the whole function cannot be used: if the macro can be
expanded several times in one function, the label will be multiply
defined in that function. A local label avoids this problem. For
example:
#define SEARCH(array, target) \ ({ \ __label__ found; \ typeof (target) _SEARCH_target = (target); \ typeof (*(array)) *_SEARCH_array = (array); \ int i, j; \ int value; \ for (i = 0; i < max; i++) \ for (j = 0; j < max; j++) \ if (_SEARCH_array[i][j] == _SEARCH_target) \ { value = i; goto found; } \ value = -1; \ found: \ value; \ })
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can get the address of a label defined in the current function
(or a containing function) with the unary operator ‘&&’. The
value has type void *
. This value is a constant and can be used
wherever a constant of that type is valid. For example:
void *ptr; … ptr = &&foo;
To use these values, you need to be able to jump to one. This is done
with the computed goto statement(1), goto *exp;
. For example,
goto *ptr;
Any expression of type void *
is allowed.
One way of using these constants is in initializing a static array that will serve as a jump table:
static void *array[] = { &&foo, &&bar, &&hack };
Then you can select a label with indexing, like this:
goto *array[i];
Note that this does not check whether the subscript is in bounds—array indexing in C never does that.
Such an array of label values serves a purpose much like that of the
switch
statement. The switch
statement is cleaner, so
use that rather than an array unless the problem does not fit a
switch
statement very well.
Another use of label values is in an interpreter for threaded code. The labels within the interpreter function can be stored in the threaded code for super-fast dispatching.
You can use this mechanism to jump to code in a different function. If you do that, totally unpredictable things will happen. The best way to avoid this is to store the label address only in automatic variables and never pass it as an argument.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A nested function is a function defined inside another function.
(Nested functions are not supported for GNU C++.) The nested function’s
name is local to the block where it is defined. For example, here we
define a nested function named square
, and call it twice:
foo (double a, double b) { double square (double z) { return z * z; } return square (a) + square (b); }
The nested function can access all the variables of the containing
function that are visible at the point of its definition. This is
called lexical scoping. For example, here we show a nested
function which uses an inherited variable named offset
:
bar (int *array, int offset, int size) { int access (int *array, int index) { return array[index + offset]; } int i; … for (i = 0; i < size; i++) … access (array, i) … }
Nested function definitions are permitted within functions in the places where variable definitions are allowed; that is, in any block, before the first statement in the block.
It is possible to call the nested function from outside the scope of its name by storing its address or passing the address to another function:
hack (int *array, int size) { void store (int index, int value) { array[index] = value; } intermediate (store, size); }
Here, the function intermediate
receives the address of
store
as an argument. If intermediate
calls store
,
the arguments given to store
are used to store into array
.
But this technique works only so long as the containing function
(hack
, in this example) does not exit.
If you try to call the nested function through its address after the containing function has exited, all hell will break loose. If you try to call it after a containing scope level has exited, and if it refers to some of the variables that are no longer in scope, you may be lucky, but it’s not wise to take the risk. If, however, the nested function does not refer to anything that has gone out of scope, you should be safe.
GNU CC implements taking the address of a nested function using a technique called trampolines. A paper describing them is available from ‘maya.idiap.ch’ in directory ‘pub/tmb’, file ‘usenix88-lexic.ps.Z’.
A nested function can jump to a label inherited from a containing
function, provided the label was explicitly declared in the containing
function (see section Locally Declared Labels). Such a jump returns instantly to the
containing function, exiting the nested function which did the
goto
and any intermediate functions as well. Here is an example:
bar (int *array, int offset, int size)
{
__label__ failure;
int access (int *array, int index)
{
if (index > size)
goto failure;
return array[index + offset];
}
int i;
…
for (i = 0; i < size; i++)
… access (array, i) …
…
return 0;
/* Control comes here from access
if it detects an error. */
failure:
return -1;
}
A nested function always has internal linkage. Declaring one with
extern
is erroneous. If you need to declare the nested function
before its definition, use auto
(which is otherwise meaningless
for function declarations).
bar (int *array, int offset, int size) { __label__ failure; auto int access (int *, int); … int access (int *array, int index) { if (index > size) goto failure; return array[index + offset]; } … }
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Using the built-in functions described below, you can record the arguments a function received, and call another function with the same arguments, without knowing the number or types of the arguments.
You can also record the return value of that function call, and later return that value, without knowing what data type the function tried to return (as long as your caller expects that data type).
__builtin_apply_args ()
This built-in function returns a pointer of type void *
to data
describing how to perform a call with the same arguments as were passed
to the current function.
The function saves the arg pointer register, structure value address, and all registers that might be used to pass arguments to a function into a block of memory allocated on the stack. Then it returns the address of that block.
__builtin_apply (function, arguments, size)
This built-in function invokes function (type void (*)()
)
with a copy of the parameters described by arguments (type
void *
) and size (type int
).
The value of arguments should be the value returned by
__builtin_apply_args
. The argument size specifies the size
of the stack argument data, in bytes.
This function returns a pointer of type void *
to data describing
how to return whatever value was returned by function. The data
is saved in a block of memory allocated on the stack.
It is not always simple to compute the proper value for size. The
value is used by __builtin_apply
to compute the amount of data
that should be pushed on the stack and copied from the incoming argument
area.
__builtin_return (result)
This built-in function returns the value described by result from
the containing function. You should specify, for result, a value
returned by __builtin_apply
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can give a name to the type of an expression using a typedef
declaration with an initializer. Here is how to define name as a
type name for the type of exp:
typedef name = exp;
This is useful in conjunction with the statements-within-expressions feature. Here is how the two together can be used to define a safe “maximum” macro that operates on any arithmetic type:
#define max(a,b) \ ({typedef _ta = (a), _tb = (b); \ _ta _a = (a); _tb _b = (b); \ _a > _b ? _a : _b; })
The reason for using names that start with underscores for the local
variables is to avoid conflicts with variable names that occur within the
expressions that are substituted for a
and b
. Eventually we
hope to design a new form of declaration syntax that allows you to declare
variables whose scopes start only after their initializers; this will be a
more reliable way to prevent such conflicts.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
typeof
Another way to refer to the type of an expression is with typeof
.
The syntax of using of this keyword looks like sizeof
, but the
construct acts semantically like a type name defined with typedef
.
There are two ways of writing the argument to typeof
: with an
expression or with a type. Here is an example with an expression:
typeof (x[0](1))
This assumes that x
is an array of functions; the type described
is that of the values of the functions.
Here is an example with a typename as the argument:
typeof (int *)
Here the type described is that of pointers to int
.
If you are writing a header file that must work when included in ANSI C
programs, write __typeof__
instead of typeof
.
See section Alternate Keywords.
A typeof
-construct can be used anywhere a typedef name could be
used. For example, you can use it in a declaration, in a cast, or inside
of sizeof
or typeof
.
y
with the type of what x
points to.
typeof (*x) y;
y
as an array of such values.
typeof (*x) y[4];
y
as an array of pointers to characters:
typeof (typeof (char *)[4]) y;
It is equivalent to the following traditional C declaration:
char *y[4];
To see the meaning of the declaration using typeof
, and why it
might be a useful way to write, let’s rewrite it with these macros:
#define pointer(T) typeof(T *) #define array(T, N) typeof(T [N])
Now the declaration can be rewritten this way:
array (pointer (char), 4) y;
Thus, array (pointer (char), 4)
is the type of arrays of 4
pointers to char
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Compound expressions, conditional expressions and casts are allowed as lvalues provided their operands are lvalues. This means that you can take their addresses or store values into them.
For example, a compound expression can be assigned, provided the last expression in the sequence is an lvalue. These two expressions are equivalent:
(a, b) += 5 a, (b += 5)
Similarly, the address of the compound expression can be taken. These two expressions are equivalent:
&(a, b) a, &b
A conditional expression is a valid lvalue if its type is not void and the true and false branches are both valid lvalues. For example, these two expressions are equivalent:
(a ? b : c) = 5 (a ? b = 5 : (c = 5))
A cast is a valid lvalue if its operand is an lvalue. A simple
assignment whose left-hand side is a cast works by converting the
right-hand side first to the specified type, then to the type of the
inner left-hand side expression. After this is stored, the value is
converted back to the specified type to become the value of the
assignment. Thus, if a
has type char *
, the following two
expressions are equivalent:
(int)a = 5 (int)(a = (char *)(int)5)
An assignment-with-arithmetic operation such as ‘+=’ applied to a cast performs the arithmetic using the type resulting from the cast, and then continues as in the previous case. Therefore, these two expressions are equivalent:
(int)a += 5 (int)(a = (char *)(int) ((int)a + 5))
You cannot take the address of an lvalue cast, because the use of its
address would not work out coherently. Suppose that &(int)f
were
permitted, where f
has type float
. Then the following
statement would try to store an integer bit-pattern where a floating
point number belongs:
*&(int)f = 1;
This is quite different from what (int)f = 1
would do—that
would convert 1 to floating point and store it. Rather than cause this
inconsistency, we think it is better to prohibit use of ‘&’ on a cast.
If you really do want an int *
pointer with the address of
f
, you can simply write (int *)&f
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression.
Therefore, the expression
x ? : y
has the value of x
if that is nonzero; otherwise, the value of
y
.
This example is perfectly equivalent to
x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C supports data types for integers that are twice as long as
long int
. Simply write long long int
for a signed
integer, or unsigned long long int
for an unsigned integer.
To make an integer constant of type long long int
, add the suffix
LL
to the integer. To make an integer constant of type
unsigned long long int
, add the suffix ULL
to the integer.
You can use these types in arithmetic like any other integer types. Addition, subtraction, and bitwise boolean operations on these types are open-coded on all types of machines. Multiplication is open-coded if the machine supports fullword-to-doubleword a widening multiply instruction. Division and shifts are open-coded only on machines that provide special support. The operations that are not open-coded use special library routines that come with GNU CC.
There may be pitfalls when you use long long
types for function
arguments, unless you declare function prototypes. If a function
expects type int
for its argument, and you pass a value of type
long long int
, confusion will result because the caller and the
subroutine will disagree about the number of bytes for the argument.
Likewise, if the function expects long long int
and you pass
int
. The best way to avoid such problems is to use prototypes.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C supports complex data types. You can declare both complex integer
types and complex floating types, using the keyword __complex__
.
For example, ‘__complex__ double x;’ declares x
as a
variable whose real part and imaginary part are both of type
double
. ‘__complex__ short int y;’ declares y
to
have real and imaginary parts of type short int
; this is not
likely to be useful, but it shows that the set of complex types is
complete.
To write a constant with a complex data type, use the suffix ‘i’ or
‘j’ (either one; they are equivalent). For example, 2.5fi
has type __complex__ float
and 3i
has type
__complex__ int
. Such a constant always has a pure imaginary
value, but you can form any complex value you like by adding one to a
real constant.
To extract the real part of a complex-valued expression exp, write
__real__ exp
. Likewise, use __imag__
to
extract the imaginary part.
The operator ‘~’ performs complex conjugation when used on a value with a complex type.
GNU CC can allocate complex automatic variables in a noncontiguous
fashion; it’s even possible for the real part to be in a register while
the imaginary part is on the stack (or vice-versa). None of the
supported debugging info formats has a way to represent noncontiguous
allocation like this, so GNU CC describes a noncontiguous complex
variable as if it were two separate variables of noncomplex type.
If the variable’s actual name is foo
, the two fictitious
variables are named foo$real
and foo$imag
. You can
examine and set these two fictitious variables with your debugger.
A future version of GDB will know how to recognize such pairs and treat them as a single variable with a complex type.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure which is really a header for a variable-length object:
struct line { int length; char contents[0]; }; { struct line *thisline = (struct line *) malloc (sizeof (struct line) + this_length); thisline->length = this_length; }
In standard C, you would have to give contents
a length of 1, which
means either you waste space or complicate the argument to malloc
.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Variable-length automatic arrays are allowed in GNU C. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the brace-level is exited. For example:
FILE * concat_fopen (char *s1, char *s2, char *mode) { char str[strlen (s1) + strlen (s2) + 1]; strcpy (str, s1); strcat (str, s2); return fopen (str, mode); }
Jumping or breaking out of the scope of the array name deallocates the storage. Jumping into the scope is not allowed; you get an error message for it.
You can use the function alloca
to get an effect much like
variable-length arrays. The function alloca
is available in
many other C implementations (but not in all). On the other hand,
variable-length arrays are more elegant.
There are other differences between these two methods. Space allocated
with alloca
exists until the containing function returns.
The space for a variable-length array is deallocated as soon as the array
name’s scope ends. (If you use both variable-length arrays and
alloca
in the same function, deallocation of a variable-length array
will also deallocate anything more recently allocated with alloca
.)
You can also use variable-length arrays as arguments to functions:
struct entry tester (int len, char data[len][len]) { … }
The length of an array is computed once when the storage is allocated
and is remembered for the scope of the array in case you access it with
sizeof
.
If you want to pass the array first and the length afterward, you can use a forward declaration in the parameter list—another GNU extension.
struct entry tester (int len; char data[len][len], int len) { … }
The ‘int len’ before the semicolon is a parameter forward
declaration, and it serves the purpose of making the name len
known when the declaration of data
is parsed.
You can write any number of such parameter forward declarations in the parameter list. They can be separated by commas or semicolons, but the last one must end with a semicolon, which is followed by the “real” parameter declarations. Each forward declaration must match a “real” declaration in parameter name and data type.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In GNU C, a macro can accept a variable number of arguments, much as a function can. The syntax for defining the macro looks much like that used for a function. Here is an example:
#define eprintf(format, args...) \ fprintf (stderr, format , ## args)
Here args
is a rest argument: it takes in zero or more
arguments, as many as the call contains. All of them plus the commas
between them form the value of args
, which is substituted into
the macro body where args
is used. Thus, we have this expansion:
eprintf ("%s:%d: ", input_file_name, line_number) → fprintf (stderr, "%s:%d: " , input_file_name, line_number)
Note that the comma after the string constant comes from the definition
of eprintf
, whereas the last comma comes from the value of
args
.
The reason for using ‘##’ is to handle the case when args
matches no arguments at all. In this case, args
has an empty
value. In this case, the second comma in the definition becomes an
embarrassment: if it got through to the expansion of the macro, we would
get something like this:
fprintf (stderr, "success!\n" , )
which is invalid C syntax. ‘##’ gets rid of the comma, so we get the following instead:
fprintf (stderr, "success!\n")
This is a special feature of the GNU C preprocessor: ‘##’ before a rest argument that is empty discards the preceding sequence of non-whitespace characters from the macro definition. (If another macro argument precedes, none of it is discarded.)
It might be better to discard the last preprocessor token instead of the last preceding sequence of non-whitespace characters; in fact, we may someday change this feature to do so. We advise you to write the macro definition so that the preceding sequence of non-whitespace characters is just a single token, so that the meaning will not change if we change the definition of this feature.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Subscripting is allowed on arrays that are not lvalues, even though the unary ‘&’ operator is not. For example, this is valid in GNU C though not valid in other C dialects:
struct foo {int a[4];}; struct foo f(); bar (int index) { return f().a[index]; }
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
void
- and Function-PointersIn GNU C, addition and subtraction operations are supported on pointers to
void
and on pointers to functions. This is done by treating the
size of a void
or of a function as 1.
A consequence of this is that sizeof
is also allowed on void
and on function types, and returns 1.
The option ‘-Wpointer-arith’ requests a warning if these extensions are used.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The elements of an aggregate initializer for an automatic variable are not required to be constant expressions in GNU C. Here is an example of an initializer with run-time varying elements:
foo (float f, float g) { float beat_freqs[2] = { f-g, f+g }; … }
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C supports constructor expressions. A constructor looks like a cast containing an initializer. Its value is an object of the type specified in the cast, containing the elements specified in the initializer.
Usually, the specified type is a structure. Assume that
struct foo
and structure
are declared as shown:
struct foo {int a; char b[2];} structure;
Here is an example of constructing a struct foo
with a constructor:
structure = ((struct foo) {x + y, 'a', 0});
This is equivalent to writing the following:
{ struct foo temp = {x + y, 'a', 0}; structure = temp; }
You can also construct an array. If all the elements of the constructor are (made up of) simple constant expressions, suitable for use in initializers, then the constructor is an lvalue and can be coerced to a pointer to its first element, as shown here:
char **foo = (char *[]) { "x", "y", "z" };
Array constructors whose elements are not simple constants are
not very useful, because the constructor is not an lvalue. There
are only two valid ways to use it: to subscript it, or initialize
an array variable with it. The former is probably slower than a
switch
statement, while the latter does the same thing an
ordinary C initializer would do. Here is an example of
subscripting an array constructor:
output = ((int[]) { 2, x, 28 }) [input];
Constructor expressions for scalar types and union types are is also allowed, but then the constructor expression is equivalent to a cast.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
Standard C requires the elements of an initializer to appear in a fixed order, the same as the order of the elements in the array or structure being initialized.
In GNU C you can give the elements in any order, specifying the array indices or structure field names they apply to.
To specify an array index, write ‘[index] =’ before the element value. For example,
int a[6] = { [4] = 29, [2] = 15 };
is equivalent to
int a[6] = { 0, 0, 15, 0, 29, 0 };
The index values must be constant expressions, even if the array being initialized is automatic.
In a structure initializer, specify the name of a field to initialize with ‘fieldname:’ before the element value. For example, given the following structure,
struct point { int x, y; };
the following initialization
struct point p = { y: yvalue, x: xvalue };
is equivalent to
struct point p = { xvalue, yvalue };
Another syntax which has the same meaning is ‘.fieldname =’., as shown here:
struct point p = { .y = yvalue, .x = xvalue };
You can also use an element label (with either the colon syntax or the period-equal syntax) when initializing a union, to specify which element of the union should be used. For example,
union foo { int i; double d; }; union foo f = { d: 4 };
will convert 4 to a double
to store it in the union using
the second element. By contrast, casting 4 to type union foo
would store it into the union as the integer i
, since it is
an integer. (See section Cast to a Union Type.)
You can combine this technique of naming elements with ordinary C initialization of successive elements. Each initializer element that does not have a label applies to the next consecutive element of the array or structure. For example,
int a[6] = { [1] = v1, v2, [4] = v4 };
is equivalent to
int a[6] = { 0, v1, v2, 0, v4, 0 };
Labeling the elements of an array initializer is especially useful
when the indices are characters or belong to an enum
type.
For example:
int whitespace[256] = { [' '] = 1, ['\t'] = 1, ['\h'] = 1, ['\f'] = 1, ['\n'] = 1, ['\r'] = 1 };
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can specify a range of consecutive values in a single case
label,
like this:
case low ... high:
This has the same effect as the proper number of individual case
labels, one for each integer value from low to high, inclusive.
This feature is especially useful for ranges of ASCII character codes:
case 'A' ... 'Z':
Be careful: Write spaces around the ...
, for otherwise
it may be parsed wrong when you use it with integer values. For example,
write this:
case 1 ... 5:
rather than this:
case 1...5:
Warning to C++ users: When compiling C++, you must write two dots ‘..’ rather than three to specify a range in case statements, thus:
case 'A' .. 'Z':This is an anachronism in the GNU C++ front end, and will be rectified in a future release.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
A cast to union type is similar to other casts, except that the type
specified is a union type. You can specify the type either with
union tag
or with a typedef name. A cast to union is actually
a constructor though, not a cast, and hence does not yield an lvalue like
normal casts. (See section Constructor Expressions.)
The types that may be cast to the union type are those of the members of the union. Thus, given the following union and variables:
union foo { int i; double d; }; int x; double y;
both x
and y
can be cast to type union
foo.
Using the cast as the right-hand side of an assignment to a variable of union type is equivalent to storing in a member of the union:
union foo u; … u = (union foo) x ≡ u.i = x u = (union foo) y ≡ u.d = y
You can also use the union cast as a function argument:
void hack (union foo); … hack ((union foo) x);
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In GNU C, you declare certain things about functions called in your program which help the compiler optimize function calls and check your code more carefully.
The keyword __attribute__
allows you to specify special
attributes when making a declaration. This keyword is followed by an
attribute specification inside double parentheses. Three attributes,
noreturn
, const
and format
, are currently defined
for functions. Others are implemented for variables and structure fields
(see section Specifying Attributes of Variables).
noreturn
A few standard library functions, such as abort
and exit
,
cannot return. GNU CC knows this automatically. Some programs define
their own functions that never return. You can declare them
noreturn
to tell the compiler this fact. For example,
void fatal () __attribute__ ((noreturn));
void
fatal (…)
{
… /* Print error message. */ …
exit (1);
}
The noreturn
keyword tells the compiler to assume that
fatal
cannot return. It can then optimize without regard to what
would happen if fatal
ever did return. This makes slightly
better code. More importantly, it helps avoid spurious warnings of
uninitialized variables.
Do not assume that registers saved by the calling function are
restored before calling the noreturn
function.
It does not make sense for a noreturn
function to have a return
type other than void
.
The attribute noreturn
is not implemented in GNU C versions
earlier than 2.5. An alternative way to declare that a function does
not return, which works in the current version and in some older
versions, is as follows:
typedef void voidfn (); volatile voidfn fatal;
const
Many functions do not examine any values except their arguments, and
have no effects except the return value. Such a function can be subject
to common subexpression elimination and loop optimization just as an
arithmetic operator would be. These functions should be declared
with the attribute const
. For example,
int square (int) __attribute__ ((const));
says that the hypothetical function square
is safe to call
fewer times than the program says.
The attribute const
is not implemented in GNU C versions earlier
than 2.5. An alternative way to declare that a function has no side
effects, which works in the current version and in some older versions,
is as follows:
typedef int intfn (); extern const intfn square;
Note that a function that has pointer arguments and examines the data
pointed to must not be declared const
. Likewise, a
function that calls a non-const
function usually must not be
const
. It does not make sense for a const
function to
return void
.
format (archetype, string-index, first-to-check)
The format
attribute specifies that a function takes printf
or scanf
style arguments which should be type-checked against a
format string. For example, the declaration:
extern int my_printf (void *my_object, const char *my_format, ...) __attribute__ ((format (printf, 2, 3)));
causes the compiler to check the arguments in calls to my_printf
for consistency with the printf
style format string argument
my_format
.
The parameter archetype determines how the format string is
interpreted, and should be either printf
or scanf
. The
parameter string-index specifies which argument is the format
string argument (starting from 1), while first-to-check is the
number of the first argument to check against the format string. For
functions where the arguments are not available to be checked (such as
vprintf
), specify the third parameter as zero. In this case the
compiler only checks the format string for consistency.
In the example above, the format string (my_format
) is the second
argument of the function my_print
, and the arguments to check
start with the third argument, so the correct parameters for the format
attribute are 2 and 3.
The format
attribute allows you to identify your own functions
which take format strings as arguments, so that GNU CC can check the
calls to these functions for errors. The compiler always checks formats
for the ANSI library functions printf
, fprintf
,
sprintf
, scanf
, fscanf
, sscanf
,
vprintf
, vfprintf
and vsprintf
whenever such
warnings are requested (using ‘-Wformat’), so there is no need to
modify the header file ‘stdio.h’.
You can specify multiple attributes in a declaration by separating them by commas within the double parentheses. Currently it is never useful to do this for a function, but it can be useful for a variable.
Some people object to the __attribute__
feature, suggesting that ANSI C’s
#pragma
should be used instead. There are two reasons for not
doing this.
#pragma
commands from a macro.
#pragma
might mean in another
compiler.
These two reasons apply to almost any application that might be proposed
for #pragma
. It is basically a mistake to use #pragma
for
anything.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C extends ANSI C to allow a function prototype to override a later old-style non-prototype definition. Consider the following example:
/* Use prototypes unless the compiler is old-fashioned. */ #if __STDC__ #define P(x) x #else #define P(x) () #endif /* Prototype function declaration. */ int isroot P((uid_t)); /* Old-style function definition. */ int isroot (x) /* ??? lossage here ??? */ uid_t x; { return x == 0; }
Suppose the type uid_t
happens to be short
. ANSI C does
not allow this example, because subword arguments in old-style
non-prototype definitions are promoted. Therefore in this example the
function definition’s argument is really an int
, which does not
match the prototype argument type of short
.
This restriction of ANSI C makes it hard to write code that is portable
to traditional C compilers, because the programmer does not know
whether the uid_t
type is short
, int
, or
long
. Therefore, in cases like these GNU C allows a prototype
to override a later old-style definition. More precisely, in GNU C, a
function prototype argument type overrides the argument type specified
by a later old-style definition if the former type is the same as the
latter type before promotion. Thus in GNU C the above example is
equivalent to the following:
int isroot (uid_t); int isroot (uid_t x) { return x == 0; }
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In GNU C, you may use dollar signs in identifier names. This is because many traditional C implementations allow such identifiers.
On some machines, dollar signs are allowed in identifiers if you specify ‘-traditional’. On a few systems they are allowed by default, even if you do not use ‘-traditional’. But they are never allowed if you specify ‘-ansi’.
There are certain ANSI C programs (obscure, to be sure) that would compile incorrectly if dollar signs were permitted in identifiers. For example:
#define foo(a) #a #define lose(b) foo (b) #define test$ lose (test)
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can use the sequence ‘\e’ in a string or character constant to stand for the ASCII character <ESC>.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The keyword __alignof__
allows you to inquire about how an object
is aligned, or the minimum alignment usually required by a type. Its
syntax is just like sizeof
.
For example, if the target machine requires a double
value to be
aligned on an 8-byte boundary, then __alignof__ (double)
is 8.
This is true on many RISC machines. On more traditional machine
designs, __alignof__ (double)
is 4 or even 2.
Some machines never actually require alignment; they allow reference to any
data type even at an odd addresses. For these machines, __alignof__
reports the recommended alignment of a type.
When the operand of __alignof__
is an lvalue rather than a type, the
value is the largest alignment that the lvalue is known to have. It may
have this alignment as a result of its data type, or because it is part of
a structure and inherits alignment from that structure. For example, after
this declaration:
struct foo { int x; char y; } foo1;
the value of __alignof__ (foo1.y)
is probably 2 or 4, the same as
__alignof__ (int)
, even though the data type of foo1.y
does not itself demand any alignment.
A related feature which lets you specify the alignment of an object is
__attribute__ ((aligned (alignment)))
; see the following
section.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The keyword __attribute__
allows you to specify special
attributes of variables or structure fields. This keyword is followed
by an attribute specification inside double parentheses. Four
attributes are currently defined: aligned
, format
,
mode
and packed
. format
is used for functions,
and thus not documented here; see Declaring Attributes of Functions.
aligned (alignment)
This attribute specifies a minimum alignment for the variable or structure field, measured in bytes. For example, the declaration:
int x __attribute__ ((aligned (16))) = 0;
causes the compiler to allocate the global variable x
on a
16-byte boundary. On a 68040, this could be used in conjunction with
an asm
expression to access the move16
instruction which
requires 16-byte aligned operands.
You can also specify the alignment of structure fields. For example, to
create a double-word aligned int
pair, you could write:
struct foo { int x[2] __attribute__ ((aligned (8))); };
This is an alternative to creating a union with a double
member
that forces the union to be double-word aligned.
It is not possible to specify the alignment of functions; the alignment of functions is determined by the machine’s requirements and cannot be changed. You cannot specify alignment for a typedef name because such a name is just an alias, not a distinct type.
The aligned
attribute can only increase the alignment; but you
can decrease it by specifying packed
as well. See below.
The linker of your operating system imposes a maximum alignment. If the linker aligns each object file on a four byte boundary, then it is beyond the compiler’s power to cause anything to be aligned to a larger boundary than that. For example, if the linker happens to put this object file at address 136 (eight more than a multiple of 64), then the compiler cannot guarantee an alignment of more than 8 just by aligning variables in the object file.
mode (mode)
This attribute specifies the data type for the declaration—whichever type corresponds to the mode mode. This in effect lets you request an integer or floating point type according to its width.
packed
The packed
attribute specifies that a variable or structure field
should have the smallest possible alignment—one byte for a variable,
and one bit for a field, unless you specify a larger value with the
aligned
attribute.
To specify multiple attributes, separate them by commas within the double parentheses: for example, ‘__attribute__ ((aligned (16), packed))’.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
By declaring a function inline
, you can direct GNU CC to
integrate that function’s code into the code for its callers. This
makes execution faster by eliminating the function-call overhead; in
addition, if any of the actual argument values are constant, their known
values may permit simplifications at compile time so that not all of the
inline function’s code needs to be included. The effect on code size is
less predictable; object code may be larger or smaller with function
inlining, depending on the particular case. Inlining of functions is an
optimization and it really “works” only in optimizing compilation. If
you don’t use ‘-O’, no function is really inline.
To declare a function inline, use the inline
keyword in its
declaration, like this:
inline int inc (int *a) { (*a)++; }
(If you are writing a header file to be included in ANSI C programs, write
__inline__
instead of inline
. See section Alternate Keywords.)
You can also make all “simple enough” functions inline with the option ‘-finline-functions’. Note that certain usages in a function definition can make it unsuitable for inline substitution.
For C++ programs, GNU CC automatically inlines member functions even if
they are not explicitly declared inline
.
(You can override this with ‘-fno-default-inline’;
@pxref{C++ Dialect Options,,Options Controlling C++ Dialect}.)
When a function is both inline and static
, if all calls to the
function are integrated into the caller, and the function’s address is
never used, then the function’s own assembler code is never referenced.
In this case, GNU CC does not actually output assembler code for the
function, unless you specify the option ‘-fkeep-inline-functions’.
Some calls cannot be integrated for various reasons (in particular,
calls that precede the function’s definition cannot be integrated, and
neither can recursive calls within the definition). If there is a
nonintegrated call, then the function is compiled to assembler code as
usual. The function must also be compiled as usual if the program
refers to its address, because that can’t be inlined.
When an inline function is not static
, then the compiler must assume
that there may be calls from other source files; since a global symbol can
be defined only once in any program, the function must not be defined in
the other source files, so the calls therein cannot be integrated.
Therefore, a non-static
inline function is always compiled on its
own in the usual fashion.
If you specify both inline
and extern
in the function
definition, then the definition is used only for inlining. In no case
is the function compiled on its own, not even if you refer to its
address explicitly. Such an address becomes an external reference, as
if you had only declared the function, and had not defined it.
This combination of inline
and extern
has almost the
effect of a macro. The way to use it is to put a function definition in
a header file with these keywords, and put another copy of the
definition (lacking inline
and extern
) in a library file.
The definition in the header file will cause most calls to the function
to be inlined. If any uses of the function remain, they will refer to
the single copy in the library.
GNU C does not inline any functions when not optimizing. It is not clear whether it is better to inline or not, in this case, but we found that a correct implementation when not optimizing was difficult. So we did the easy thing, and turned it off.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
In an assembler instruction using asm
, you can now specify the
operands of the instruction using C expressions. This means no more
guessing which registers or memory locations will contain the data you want
to use.
You must specify an assembler instruction template much like what appears in a machine description, plus an operand constraint string for each operand.
For example, here is how to use the 68881’s fsinx
instruction:
asm ("fsinx %1,%0" : "=f" (result) : "f" (angle));
Here angle
is the C expression for the input operand while
result
is that of the output operand. Each has ‘"f"’ as its
operand constraint, saying that a floating point register is required. The
‘=’ in ‘=f’ indicates that the operand is an output; all output
operands’ constraints must use ‘=’. The constraints use the same
language used in the machine description (@pxref{Constraints}).
Each operand is described by an operand-constraint string followed by the C expression in parentheses. A colon separates the assembler template from the first output operand, and another separates the last output operand from the first input, if any. Commas separate output operands and separate inputs. The total number of operands is limited to ten or to the maximum number of operands in any instruction pattern in the machine description, whichever is greater.
If there are no output operands, and there are input operands, then there must be two consecutive colons surrounding the place where the output operands would go.
Output operand expressions must be lvalues; the compiler can check this.
The input operands need not be lvalues. The compiler cannot check whether
the operands have data types that are reasonable for the instruction being
executed. It does not parse the assembler instruction template and does
not know what it means, or whether it is valid assembler input. The
extended asm
feature is most often used for machine instructions
that the compiler itself does not know exist.
The output operands must be write-only; GNU CC will assume that the values in these operands before the instruction are dead and need not be generated. Extended asm does not support input-output or read-write operands. For this reason, the constraint character ‘+’, which indicates such an operand, may not be used.
When the assembler instruction has a read-write operand, or an operand
in which only some of the bits are to be changed, you must logically
split its function into two separate operands, one input operand and one
write-only output operand. The connection between them is expressed by
constraints which say they need to be in the same location when the
instruction executes. You can use the same C expression for both
operands, or different expressions. For example, here we write the
(fictitious) ‘combine’ instruction with bar
as its read-only
source operand and foo
as its read-write destination:
asm ("combine %2,%0" : "=r" (foo) : "0" (foo), "g" (bar));
The constraint ‘"0"’ for operand 1 says that it must occupy the same location as operand 0. A digit in constraint is allowed only in an input operand, and it must refer to an output operand.
Only a digit in the constraint can guarantee that one operand will be in
the same place as another. The mere fact that foo
is the value of
both operands is not enough to guarantee that they will be in the same
place in the generated assembler code. The following would not work:
asm ("combine %2,%0" : "=r" (foo) : "r" (foo), "g" (bar));
Various optimizations or reloading could cause operands 0 and 1 to be in
different registers; GNU CC knows no reason not to do so. For example, the
compiler might find a copy of the value of foo
in one register and
use it for operand 1, but generate the output operand 0 in a different
register (copying it afterward to foo
’s own address). Of course,
since the register for operand 1 is not even mentioned in the assembler
code, the result will not work, but GNU CC can’t tell that.
Some instructions clobber specific hard registers. To describe this, write a third colon after the input operands, followed by the names of the clobbered hard registers (given as strings). Here is a realistic example for the Vax:
asm volatile ("movc3 %0,%1,%2" : /* no outputs */ : "g" (from), "g" (to), "g" (count) : "r0", "r1", "r2", "r3", "r4", "r5");
If you refer to a particular hardware register from the assembler code, then you will probably have to list the register after the third colon to tell the compiler that the register’s value is modified. In many assemblers, the register names begin with ‘%’; to produce one ‘%’ in the assembler code, you must write ‘%%’ in the input.
If your assembler instruction can alter the condition code register, add ‘cc’ to the list of clobbered registers. GNU CC on some machines represents the condition codes as a specific hardware register; ‘cc’ serves to name this register. On other machines, the condition code is handled differently, and specifying ‘cc’ has no effect. But it is valid no matter what the machine.
If your assembler instruction modifies memory in an unpredictable fashion, add ‘memory’ to the list of clobbered registers. This will cause GNU CC to not keep memory values cached in registers across the assembler instruction.
You can put multiple assembler instructions together in a single asm
template, separated either with newlines (written as ‘\n’) or with
semicolons if the assembler allows such semicolons. The GNU assembler
allows semicolons and all Unix assemblers seem to do so. The input
operands are guaranteed not to use any of the clobbered registers, and
neither will the output operands’ addresses, so you can read and write the
clobbered registers as many times as you like. Here is an example of
multiple instructions in a template; it assumes that the subroutine
_foo
accepts arguments in registers 9 and 10:
asm ("movl %0,r9;movl %1,r10;call _foo" : /* no outputs */ : "g" (from), "g" (to) : "r9", "r10");
Unless an output operand has the ‘&’ constraint modifier, GNU CC may allocate it in the same register as an unrelated input operand, on the assumption that the inputs are consumed before the outputs are produced. This assumption may be false if the assembler code actually consists of more than one instruction. In such a case, use ‘&’ for each output operand that may not overlap an input. @xref{Modifiers}.
If you want to test the condition code produced by an assembler instruction,
you must include a branch and a label in the asm
construct, as follows:
asm ("clr %0;frob %1;beq 0f;mov #1,%0;0:" : "g" (result) : "g" (input));
This assumes your assembler supports local labels, as the GNU assembler and most Unix assemblers do.
Speaking of labels, jumps from one asm
to another are not
supported. The compiler’s optimizers do not know about these jumps,
and therefore they cannot take account of them when deciding how to
optimize.
Usually the most convenient way to use these asm
instructions is to
encapsulate them in macros that look like functions. For example,
#define sin(x) \ ({ double __value, __arg = (x); \ asm ("fsinx %1,%0": "=f" (__value): "f" (__arg)); \ __value; })
Here the variable __arg
is used to make sure that the instruction
operates on a proper double
value, and to accept only those
arguments x
which can convert automatically to a double
.
Another way to make sure the instruction operates on the correct data type
is to use a cast in the asm
. This is different from using a
variable __arg
in that it converts more different types. For
example, if the desired type were int
, casting the argument to
int
would accept a pointer with no complaint, while assigning the
argument to an int
variable named __arg
would warn about
using a pointer unless the caller explicitly casts it.
If an asm
has output operands, GNU CC assumes for optimization
purposes that the instruction has no side effects except to change the
output operands. This does not mean that instructions with a side effect
cannot be used, but you must be careful, because the compiler may eliminate
them if the output operands aren’t used, or move them out of loops, or
replace two with one if they constitute a common subexpression. Also, if
your instruction does have a side effect on a variable that otherwise
appears not to change, the old value of the variable may be reused later if
it happens to be found in a register.
You can prevent an asm
instruction from being deleted, moved
significantly, or combined, by writing the keyword volatile
after
the asm
. For example:
#define set_priority(x) \ asm volatile ("set_priority %0": /* no outputs */ : "g" (x))
An instruction without output operands will not be deleted or moved significantly, regardless, unless it is unreachable.
Note that even a volatile asm
instruction can be moved in ways
that appear insignificant to the compiler, such as across jump
instructions. You can’t expect a sequence of volatile asm
instructions to remain perfectly consecutive. If you want consecutive
output, use a single asm
.
It is a natural idea to look for a way to give access to the condition code left by the assembler instruction. However, when we attempted to implement this, we found no way to make it work reliably. The problem is that output operands might need reloading, which would result in additional following “store” instructions. On most machines, these instructions would alter the condition code before there was time to test it. This problem doesn’t arise for ordinary “test” and “compare” instructions because they don’t have any output operands.
If you are writing a header file that should be includable in ANSI C
programs, write __asm__
instead of asm
. See section Alternate Keywords.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can specify the name to be used in the assembler code for a C
function or variable by writing the asm
(or __asm__
)
keyword after the declarator as follows:
int foo asm ("myfoo") = 2;
This specifies that the name to be used for the variable foo
in
the assembler code should be ‘myfoo’ rather than the usual
‘_foo’.
On systems where an underscore is normally prepended to the name of a C function or variable, this feature allows you to define names for the linker that do not start with an underscore.
You cannot use asm
in this way in a function definition; but
you can get the same effect by writing a declaration for the function
before its definition and putting asm
there, like this:
extern func () asm ("FUNC"); func (x, y) int x, y; …
It is up to you to make sure that the assembler names you choose do not conflict with any other assembler symbols. Also, you must not use a register name; that would produce completely invalid assembler code. GNU CC does not as yet have the ability to store static variables in registers. Perhaps that will be added.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C allows you to put a few global variables into specified hardware registers. You can also specify the register in which an ordinary register variable should be allocated.
These local variables are sometimes convenient for use with the extended
asm
feature (see section Assembler Instructions with C Expression Operands), if you want to write one
output of the assembler instruction directly into a particular register.
(This will work provided the register you specify fits the constraints
specified for that operand in the asm
.)
1.31.1 Defining Global Register Variables | ||
1.31.2 Specifying Registers for Local Variables |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can define a global register variable in GNU C like this:
register int *foo asm ("a5");
Here a5
is the name of the register which should be used. Choose a
register which is normally saved and restored by function calls on your
machine, so that library routines will not clobber it.
Naturally the register name is cpu-dependent, so you would need to
conditionalize your program according to cpu type. The register
a5
would be a good choice on a 68000 for a variable of pointer
type. On machines with register windows, be sure to choose a “global”
register that is not affected magically by the function call mechanism.
In addition, operating systems on one type of cpu may differ in how they
name the registers; then you would need additional conditionals. For
example, some 68000 operating systems call this register %a5
.
Eventually there may be a way of asking the compiler to choose a register automatically, but first we need to figure out how it should choose and how to enable you to guide the choice. No solution is evident.
Defining a global register variable in a certain register reserves that register entirely for this use, at least within the current compilation. The register will not be allocated for any other purpose in the functions in the current compilation. The register will not be saved and restored by these functions. Stores into this register are never deleted even if they would appear to be dead, but references may be deleted or moved or simplified.
It is not safe to access the global register variables from signal handlers, or from more than one thread of control, because the system library routines may temporarily use the register for other things (unless you recompile them specially for the task at hand).
It is not safe for one function that uses a global register variable to
call another such function foo
by way of a third function
lose
that was compiled without knowledge of this variable (i.e. in a
different source file in which the variable wasn’t declared). This is
because lose
might save the register and put some other value there.
For example, you can’t expect a global register variable to be available in
the comparison-function that you pass to qsort
, since qsort
might have put something else in that register. (If you are prepared to
recompile qsort
with the same global register variable, you can
solve this problem.)
If you want to recompile qsort
or other source files which do not
actually use your global register variable, so that they will not use that
register for any other purpose, then it suffices to specify the compiler
option ‘-ffixed-reg’. You need not actually add a global
register declaration to their source code.
A function which can alter the value of a global register variable cannot safely be called from a function compiled without this variable, because it could clobber the value the caller expects to find there on return. Therefore, the function which is the entry point into the part of the program that uses the global register variable must explicitly save and restore the value which belongs to its caller.
On most machines, longjmp
will restore to each global register
variable the value it had at the time of the setjmp
. On some
machines, however, longjmp
will not change the value of global
register variables. To be portable, the function that called setjmp
should make other arrangements to save the values of the global register
variables, and to restore them in a longjmp
. This way, the same
thing will happen regardless of what longjmp
does.
All global register variable declarations must precede all function definitions. If such a declaration could appear after function definitions, the declaration would be too late to prevent the register from being used for other purposes in the preceding functions.
Global register variables may not have initial values, because an executable file has no means to supply initial contents for a register.
On the Sparc, there are reports that g3 … g7 are suitable
registers, but certain library functions, such as getwd
, as well
as the subroutines for division and remainder, modify g3 and g4. g1 and
g2 are local temporaries.
On the 68000, a2 … a5 should be suitable, as should d2 … d7. Of course, it will not do to use more than a few of those.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can define a local register variable with a specified register like this:
register int *foo asm ("a5");
Here a5
is the name of the register which should be used. Note
that this is the same syntax used for defining global register
variables, but for a local variable it would appear within a function.
Naturally the register name is cpu-dependent, but this is not a problem, since specific registers are most often useful with explicit assembler instructions (see section Assembler Instructions with C Expression Operands). Both of these things generally require that you conditionalize your program according to cpu type.
In addition, operating systems on one type of cpu may differ in how they
name the registers; then you would need additional conditionals. For
example, some 68000 operating systems call this register %a5
.
Eventually there may be a way of asking the compiler to choose a register automatically, but first we need to figure out how it should choose and how to enable you to guide the choice. No solution is evident.
Defining such a register variable does not reserve the register; it remains available for other uses in places where flow control determines the variable’s value is not live. However, these registers are made unavailable for use in the reload pass. I would not be surprised if excessive use of this feature leaves the compiler too few available registers to compile certain functions.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The option ‘-traditional’ disables certain keywords; ‘-ansi’
disables certain others. This causes trouble when you want to use GNU C
extensions, or ANSI C features, in a general-purpose header file that
should be usable by all programs, including ANSI C programs and traditional
ones. The keywords asm
, typeof
and inline
cannot be
used since they won’t work in a program compiled with ‘-ansi’, while
the keywords const
, volatile
, signed
, typeof
and inline
won’t work in a program compiled with
‘-traditional’.
The way to solve these problems is to put ‘__’ at the beginning and
end of each problematical keyword. For example, use __asm__
instead of asm
, __const__
instead of const
, and
__inline__
instead of inline
.
Other C compilers won’t accept these alternative keywords; if you want to compile with another compiler, you can define the alternate keywords as macros to replace them with the customary keywords. It looks like this:
#ifndef __GNUC__ #define __asm__ asm #endif
‘-pedantic’ causes warnings for many GNU C extensions. You can
prevent such warnings within one expression by writing
__extension__
before the expression. __extension__
has no
effect aside from this.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
enum
TypesYou can define an enum
tag without specifying its possible values.
This results in an incomplete type, much like what you get if you write
struct foo
without describing the elements. A later declaration
which does specify the possible values completes the type.
You can’t allocate variables or storage using the type while it is incomplete. However, you can work with pointers to that type.
This extension may not be very useful, but it makes the handling of
enum
more consistent with the way struct
and union
are handled.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU CC predefines two string variables to be the name of the current function.
The variable __FUNCTION__
is the name of the function as it appears
in the source. The variable __PRETTY_FUNCTION__
is the name of
the function pretty printed in a language specific fashion.
These names are always the same in a C function, but in a C++ function they may be different. For example, this program:
extern "C" { extern int printf (char *, ...); } class a { public: sub (int i) { printf ("__FUNCTION__ = %s\n", __FUNCTION__); printf ("__PRETTY_FUNCTION__ = %s\n", __PRETTY_FUNCTION__); } }; int main (void) { a ax; ax.sub (0); return 0; }
gives this output:
__FUNCTION__ = sub __PRETTY_FUNCTION__ = int a::sub (int)
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The GNU compiler provides these extensions to the C++ language (and you
can also use most of the C language extensions in your C++ programs). If you
want to write code that checks whether these features are available, you can
test for the GNU compiler the same way as for C programs: check for a
predefined macro __GNUC__
. You can also use __GNUG__
to
test specifically for GNU C++ (see Standard Predefined Macros in The C Preprocessor).
2.1 Named Return Values in C++ | Giving a name to C++ function return values. | |
2.2 Minimum and Maximum Operators in C++ | C++ Minimum and maximum operators. | |
2.3 goto and Destructors in GNU C++ | Goto is safe to use in C++ even when destructors are needed. | |
2.4 Declarations and Definitions in One Header | You can use a single C++ header file for both declarations and definitions. |
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
GNU C++ extends the function-definition syntax to allow you to specify a name for the result of a function outside the body of the definition, in C++ programs:
type functionname (args) return resultname; { … body … }
You can use this feature to avoid an extra constructor call when
a function result has a class type. For example, consider a function
m
, declared as ‘X v = m ();’, whose result is of class
X
:
X m () { X b; b.a = 23; return b; }
Although m
appears to have no arguments, in fact it has one implicit
argument: the address of the return value. At invocation, the address
of enough space to hold v
is sent in as the implicit argument.
Then b
is constructed and its a
field is set to the value
23. Finally, a copy constructor (a constructor of the form ‘X(X&)’)
is applied to b
, with the (implicit) return value location as the
target, so that v
is now bound to the return value.
But this is wasteful. The local b
is declared just to hold
something that will be copied right out. While a compiler that
combined an “elision” algorithm with interprocedural data flow
analysis could conceivably eliminate all of this, it is much more
practical to allow you to assist the compiler in generating
efficient code by manipulating the return value explicitly,
thus avoiding the local variable and copy constructor altogether.
Using the extended GNU C++ function-definition syntax, you can avoid the
temporary allocation and copying by naming r
as your return value
as the outset, and assigning to its a
field directly:
X m () return r; { r.a = 23; }
The declaration of r
is a standard, proper declaration, whose effects
are executed before any of the body of m
.
Functions of this type impose no additional restrictions; in particular,
you can execute return
statements, or return implicitly by
reaching the end of the function body (“falling off the edge”).
Cases like
X m () return r (23); { return; }
(or even ‘X m () return r (23); { }’) are unambiguous, since
the return value r
has been initialized in either case. The
following code may be hard to read, but also works predictably:
X m () return r; { X b; return b; }
The return value slot denoted by r
is initialized at the outset,
but the statement ‘return b;’ overrides this value. The compiler
deals with this by destroying r
(calling the destructor if there
is one, or doing nothing if there is not), and then reinitializing
r
with b
.
This extension is provided primarily to help people who use overloaded operators, where there is a great need to control not just the arguments, but the return values of functions. For classes where the copy constructor incurs a heavy performance penalty (especially in the common case where there is a quick default constructor), this is a major savings. The disadvantage of this extension is that you do not control when the default constructor for the return value is called: it is always called at the beginning.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
It is very convenient to have operators which return the “minimum” or the “maximum” of two arguments. In GNU C++ (but not in GNU C),
a <? b
is the minimum, returning the smaller of the numeric values a and b;
a >? b
is the maximum, returning the larger of the numeric values a and b.
These operations are not primitive in ordinary C++, since you can use a macro to return the minimum of two things in C++, as in the following example.
#define MIN(X,Y) ((X) < (Y) ? : (X) : (Y))
You might then use ‘int min = MIN (i, j);’ to set min to the minimum value of variables i and j.
However, side effects in X
or Y
may cause unintended
behavior. For example, MIN (i++, j++)
will fail, incrementing
the smaller counter twice. A GNU C extension allows you to write safe
macros that avoid this kind of problem (see section Naming an Expression’s Type). However, writing MIN
and MAX
as
macros also forces you to use function-call notation notation for a
fundamental arithmetic operation. Using GNU C++ extensions, you can
write ‘int min = i <? j;’ instead.
Since <?
and >?
are built into the compiler, they properly
handle expressions with side-effects; ‘int min = i++ <? j++;’
works correctly.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
goto
and Destructors in GNU C++In C++ programs, you can safely use the goto
statement. When you
use it to exit a block which contains aggregates requiring destructors,
the destructors will run before the goto
transfers control. (In
ANSI C++, goto
is restricted to targets within the current
block.)
The compiler still forbids using goto
to enter a scope
that requires constructors.
[ << ] | [ < ] | [ Up ] | [ > ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
C++ object definitions can be quite complex. In principle, your source code will need two kinds of things for each object that you use across more than one source file. First, you need an interface specification, describing its structure with type declarations and function prototypes. Second, you need the implementation itself. It can be tedious to maintain a separate interface description in a header file, in parallel to the actual implementation. It is also dangerous, since separate interface and implementation definitions may not remain parallel.
With GNU C++, you can use a single header file for both purposes.
Warning: The mechanism to specify this is in transition. For the nonce, you must use one of two
#pragma
commands; in a future release of GNU C++, an alternative mechanism will make these#pragma
commands unnecessary.
The header file contains the full definitions, but is marked with
‘#pragma interface’ in the source code. This allows the compiler
to use the header file only as an interface specification when ordinary
source files incorporate it with #include
. In the single source
file where the full implementation belongs, you can use either a naming
convention or ‘#pragma implementation’ to indicate this alternate
use of the header file.
#pragma interface
Use this directive in header files that define object classes, to save space in most of the object files that use those classes. Normally, local copies of certain information (backup copies of inline member functions, debugging information, and the internal tables that implement virtual functions) must be kept in each object file that includes class definitions. You can use this pragma to avoid such duplication. When a header file containing ‘#pragma interface’ is included in a compilation, this auxiliary information will not be generated (unless the main input source file itself uses ‘#pragma implementation’). Instead, the object files will contain references to be resolved at link time.
#pragma implementation
#pragma implementation "objects.h"
Use this pragma in a main input file, when you want full output from included header files to be generated (and made globally visible). The included header file, in turn, should use ‘#pragma interface’. Backup copies of inline member functions, debugging information, and the internal tables used to implement virtual functions are all generated in implementation files.
‘#pragma implementation’ is implied whenever the basename(2) of your source file matches the basename of a header file it includes. There is no way to turn this off (other than using a different name for one of the two files). In the same vein, if you use ‘#pragma implementation’ with no argument, it applies to an include file with the same basename as your source file. For example, in ‘allclass.cc’, ‘#pragma implementation’ by itself is equivalent to ‘#pragma implementation "allclass.h"’; but even if you do not say ‘#pragma implementation’ at all, ‘allclass.h’ is treated as an implementation file whenever you include it from ‘allclass.cc’.
If you use an explicit ‘#pragma implementation’, it must appear in your source file before you include the affected header files.
Use the string argument if you want a single implementation file to include code from multiple header files. (You must also use ‘#include’ to include the header file; ‘#pragma implementation’ only specifies how to use the file—it doesn’t actually include it.)
There is no way to split up the contents of a single header file into multiple implementation files.
‘#pragma implementation’ and ‘#pragma interface’ also have an effect on function inlining.
If you define a class in a header file marked with ‘#pragma
interface’, the effect on a function defined in that class is similar to
an explicit extern
declaration—the compiler emits no code at
all to define an independent version of the function. Its definition
is used only for inlining with its callers.
Conversely, when you include the same header file in a main source file that declares it as ‘#pragma implementation’, the compiler emits code for the function itself; this defines a version of the function that can be found via pointers (or by callers compiled without inlining).
[Top] | [Contents] | [Index] | [ ? ] |
The analogous feature in Fortran is called an assigned goto, but that name seems inappropriate in C, where one can do more than simply store label addresses in label variables.
A file’s basename is the name stripped of all leading path information and of trailing suffixes, such as ‘.h’ or ‘.C’ or ‘.cc’.
[Top] | [Contents] | [Index] | [ ? ] |
This document was generated on November 4, 2022 using texi2html 5.0.
The buttons in the navigation panels have the following meaning:
Button | Name | Go to | From 1.2.3 go to |
---|---|---|---|
[ << ] | FastBack | Beginning of this chapter or previous chapter | 1 |
[ < ] | Back | Previous section in reading order | 1.2.2 |
[ Up ] | Up | Up section | 1.2 |
[ > ] | Forward | Next section in reading order | 1.2.4 |
[ >> ] | FastForward | Next chapter | 2 |
[Top] | Top | Cover (top) of document | |
[Contents] | Contents | Table of contents | |
[Index] | Index | Index | |
[ ? ] | About | About (help) |
where the Example assumes that the current position is at Subsubsection One-Two-Three of a document of the following structure:
This document was generated on November 4, 2022 using texi2html 5.0.